import { constantRouterMap } from '@/router'
import { menus } from '@/router/config'
import { menu_listAll, menu_save } from "@/api/menu";
import { Message } from 'element-ui'

const defaultMenu = [//系统默认菜单
  {
    id: 1,
    pId: 0,
    menu_code: 'addressbook',
    menu_name: '通讯录'
  },
  {
    id: 10,
    pId: 1,
    menu_code: 'addressbook_orgmain',
    menu_name: '组织架构'
  },
  {
    id: 100,
    pId: 10,
    menu_code: 'orgmain_organize',
    menu_name: '组织架构'
  },
  {
    id: 101,
    pId: 10,
    menu_code: 'orgmain_group',
    menu_name: '小组'
  },
  {
    id: 6,
    pId: 0,
    menu_code: 'sysSet',
    menu_name: '系统设置'
  },
  {
    id: 61,
    pId: 6,
    menu_code: 'sysSet_authority',
    menu_name: '权限设置'
  },
  {
    id: 611,
    pId: 61,
    menu_code: 'authority_menu',
    menu_name: '菜单列表'
  }
]

function formatMenu(cacheMenu, child) {
  let result = []
  if(!child){
    let unChild = getMenuObj(cacheMenu, menus)
    result.push(...unChild)
  }else{
    let isChild = getMenuObj(cacheMenu, child)
    result.push(...isChild)
  }
  return result;
}

function getMenuObj(cacheMenu, confMenus){ 
  let result = []
  for (let i = 0; i < confMenus.length; i++) {
    let confMenu = confMenus[i];
    let apiMenu = cacheMenu[confMenu.menu_code];
    if(apiMenu){
      let pushMenu = {...confMenu, ...apiMenu}
      pushMenu.meta.title = cacheMenu[confMenu.menu_code].menu_name;
      if(confMenu.children){
        let menuObj = {
          ...pushMenu,
          children: formatMenu(cacheMenu, confMenu.children)
        }
        //此处添加 不存在菜单列表的 其他页面
        for (let j = 0; j < confMenu.children.length; j++) {
          let childMenu = confMenu.children[j];
          if(childMenu.hidden){
            menuObj.children.push(childMenu)
          }
        }
        //此处解决当children length 有且只有一个的时候，格式化 path
        if(menuObj.children.length === 1 && menuObj.redirect === 'noredirect' && !menuObj.children[0].redirect){
          let path = menuObj.path + '/' + menuObj.children[0].path
          menuObj.redirect = path;
          menuObj.children[0].path = path
        }
        result.push(menuObj)
      }else{
        result.push(pushMenu)
      }
    }
  }
  return result;
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    routerLoadDone: false
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers);
      state.routerLoadDone = true;
    }
  },
  actions: {
    async GetMenuList({ commit }){
      const { data } = await menu_listAll({ company_id: localStorage.getItem("companyId") - 0 });
      if (data.status != 100) {
        Message.error("菜单加载异常，请联系管理员");
      }
      let cacheMenu = {}
      let result = data.data.rows;
      if(result.length == 0){//默认没有菜单，动态加载菜单设置页面
        result = defaultMenu;
        for (let i = 0; i < defaultMenu.length; i++) {
          let node = defaultMenu[i];
          let saveObj = {
            menu_name   : node.menu_name,
            menu_code   : node.menu_code,
            menu_url    : node.id,
            parent_id   : node.pId,
            company_id  : localStorage.getItem("companyId") - 0,
            close_status: 1
          }
          await menu_save(saveObj);
        }
      }
      result.forEach(item => {
        if(item.close_status == 1){
          cacheMenu[item.menu_code] = item
        }
      })
      let accessedRouters = formatMenu(cacheMenu);
      accessedRouters.push({ path: "*", redirect: "/404", hidden: true })
      commit('SET_ROUTERS', accessedRouters)
    }
  }
}

export default permission
